﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Windows.Forms;

namespace AccountingClient.AccountingServer
{
    partial class DTOTransaction
    {
        private decimal amount;
        private string involveAccounts;
        private IDictionary<int, string> accountNames;

        public DTOTransaction(): this(null)
        {
        }

        public DTOTransaction(IDictionary<int, string> accList)
        {
            PropertyChanged += delegate(object sender, System.ComponentModel.PropertyChangedEventArgs e)
                               {
                                   if (e.PropertyName == "Details")
                                   {
                                       DetailsUpdated();
                                   }
                               };
            SetAccountList(accList);
        }

        public void SetAccountList(IDictionary<int, string> list)
        {
            accountNames = list;
        }

        public void DetailsUpdated()
        {
            amount = 0;
            if (DetailsField != null)
            {
                foreach (var item in DetailsField)
                {
                    if (item.IsCredit)
                    {
                        amount += item.Amount;
                    }
                }
                StringBuilder accounts = new StringBuilder(Properties.Settings.Default.AccountSeparator);
                if (accountNames != null)
                {
                    foreach (var item in DetailsField)
                    {
                        if (item.IsCredit)
                        {
                            accounts.Append('-');
                        }
                        else
                        {
                            accounts.Append('+');
                        }
                        if (accountNames.ContainsKey(item.AccountId))
                        {
                            accounts.Append(accountNames[item.AccountId]); 
                        }
                        accounts.Append(Properties.Settings.Default.AccountSeparator);
                    } 
                }
                involveAccounts = accounts.ToString();
            }
            this.RaisePropertyChanged("Amount");
            this.RaisePropertyChanged("InvolveAccounts");
        }

        public string InvolveAccounts
        {
            get
            {
                return involveAccounts;
            }
        }

        public decimal Amount
        {
            get { return amount; }
        }
    }
}
